package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Objects;

//管理员信息页
@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminHomeController {

    @Autowired
    AdminRepository repository;
    //管理员页面相关
    @GetMapping("/list")
    public String list(HttpServletRequest request, ModelMap map){
        List<AdminInfo> adminInfoList = repository.findAll();  //查询所有用户信息
        map.put("adminList",adminList);
        Cookie[] cookies = request.getCookies();
        if(cookies !=null){
            for(Cookie cookie : cookies){
                if(cookie,getName().equals(GlobalConst.COOKIE_TOKEN)){
                    String cookieValue = cookie.getValue();
                    log.info("获取到存储的cookie={}",cookieValue);
                    if(!StringUtils.isEmpty(cookieValue)){
                        AdminInfo adminInfo = repository.findByAdminId(Integer.parseInt(cookieValue));
                        if(adminInfo != null && Objects.equals(AdminStatusEnum.SUPER_ADMIN.getCode(),adminInfo.getAdminType())){
                            map.put("isAdmin",true);
                        }
                    }
                }
            }
        }
        return "admin/list";
    }
}
//管理员详情页
@GetMapping("/index")
public String index(@RequestParam(value = "adminId",required = false) Integer adminId, ModelMap map) {
    AdminInfo adminInfo = repository.findByAdminId(adminId);  //根据管理员ID查询管理员信息
    map.put("adminInfo", adminInfo);
    map.put("enums", AdminStatusEnum.values());
    log.error("管理员={}",AdminStatusEnum.values());
    return "admin/index";

}
//保存或者更新
@PostMapping("/save")
public String save(@Valid AdminForm form,
                   BindingResult bindingResult,
                   ModelMap map){
    log.info("SellerForm={}",form);
    if (bindingResult.hasErrors()){
        map.put("msg",bindingResult.getFieldError().getDefaultMessage());
    }
}